<template>
  <div>
    <van-nav-bar
      class="app-nav-bar"
      title="注册 / 登录"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form
      :show-error="false"
      :show-error-message="false"
      validate-first
      ref="loginForm"
      @submit="login"
      @failed="loginFailed"
    >
      <van-field
        v-model="user.mobile"
        icon-prefix="icon"
        left-icon="wode"
        placeholder="请输入手机号"
        center
        name="mobile"
        :rules="formRules.mobile"
      ></van-field>
      <van-field
        v-model="user.code"
        clearable
        left-icon="music-o"
        placeholder="请输入验证码"
        center
        name="code"
        :rules="formRules.code"
      >
        <template #button>
          <van-count-down :time="time" format=" ss 秒" v-if="isShow" @finish="isShow=false"/>
          <van-button size="mini" round @click.prevent="onSendSms" v-else>发送验证码</van-button>
        </template>
      </van-field>
      <div class="login-box">
        <van-button type="info" block class="login-btn">登录</van-button>
      </div>
    </van-form>

  </div>
</template>

<script>
import { loginWay } from '../../api/login'
import { Toast } from 'vant'

export default {
  name: 'Login',
  data () {
    return {
      user: {
        mobile: '13911111111',
        code: '246810'
      },
      formRules: {
        mobile: [{
          required: true,
          message: '请填写手机号'
        },
        {
          pattern: /^1[3|4|5|7|8][0-9]{9}$/,
          message: '请输入正确的手机号'
        }
        ],
        code: [{
          required: true,
          message: '请填写验证码'
        },
        {
          pattern: /^\d{6}$/,
          message: '请输入正确的验证码'
        }
        ]
      },
      time: 60 * 1000,
      isShow: false
    }
  },
  methods: {
    login () {
      Toast.loading({
        message: '登陆中...',
        forbidClick: true,
        duration: 0
      })
      loginWay(this.user).then(res => {
        Toast.success('登陆成功')
        this.$store.commit('setUserToken', res.data.data)
      }).catch(() => {
        Toast.fail('登陆失败')
      })
    },
    loginFailed (errors) {
      Toast({
        message: errors.errors[0].message,
        position: 'top'
      })
    },
    onSendSms () {
      // this.$refs['login-form'].validate('mobile').then((data) => {
      //   console.log(data)
      // })
      this.$refs.loginForm.validate('mobile').then(() => {
        this.isShow = true
      }).catch(res => {
        Toast({
          message: res.message,
          position: 'top'
        })
      })
    }
  }
}
</script>

<style scoped lang="less">
  .login-box {
    padding: 26px 16px;

    .login-btn {
      background-color: #6db4fb;
      border: none;

      .van-button__text {
        font-size: 15px;
      }
    }
  }
</style>
